from fastapi import APIRouter, UploadFile, File

from app.schemas.generate import UploadResult
from app.schemas.response import StandardResponse
from app.utils.file_processor import FileParser

router = APIRouter()


async def _parse_and_store(material_type: str, file: UploadFile):
    """统一解析逻辑（模拟存储）"""
    # 1. 解析文件内容
    parsed = FileParser.parse_file(file)

    # 2. 模拟数据库存储（实际项目替换为真实存储逻辑）
    db_record = {
        "material_type": material_type,
        "content": parsed["content"][:1000],  # 示例：截取部分内容
        "original_name": parsed["original_name"],
        "file_type": parsed["file_type"]
    }
    print(f"模拟存储到数据库: {db_record}")  # 替换为真实数据库操作

    result = UploadResult(
        material_type=material_type,
        content_length=len(parsed["content"]),
        stored_content=db_record["content"]
    )

    return StandardResponse(
        code=200,
        message="上传成功",
        data=result
    )


@router.post("/product-materials")
async def upload_product_materials(file: UploadFile = File(...)):
    return await _parse_and_store("product", file)


@router.post("/methodology-materials")
async def upload_methodology_materials(file: UploadFile = File(...)):
    return await _parse_and_store("methodology", file)


@router.post("/script-case-materials")
async def upload_script_case_materials(file: UploadFile = File(...)):
    return await _parse_and_store("script_case", file)